<template>
  <div class="bg-white container-ymm">
    <div class="header-ymm" style="border:none">
      <el-row style="text-align:right" class="pt-10 pb-10">
        <el-button type="primary" @click="save('formsku')">保存</el-button>
        <el-button type="primary" @click="goBack()">返回</el-button>
      </el-row>

      <el-row :gutter="20" style="margin-bottom: 15px;border: 1px dashed #eee"/>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-row :gutter="1">
            <el-col :span="5">
              <div class="shipment_label" name="门店">门店：</div>
            </el-col>
            <el-col :span="15">
              <el-select v-model="form.store" value-key="storeName" placeholder class="full-width-i">
                <el-option
                  v-for="item in storeList"
                  :key="item.storeId"
                  :label="item.storeName"
                  :value="item"
                />
              </el-select>
            </el-col>
          </el-row>
        </el-col>

        <el-col :span="8">
          <el-row :gutter="1">
            <el-col :span="5">
              <div class="shipment_label" name="提货方式">提货方式：</div>
            </el-col>
            <el-col :span="15">
              <el-select v-model="form.deliveryModeItem" value-key="label" placeholder class="full-width-i">
                <el-option
                  v-for="item in deliveryModes"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                />
              </el-select>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="8">
          <el-row :gutter="1">
            <el-col :span="5">
              <div class="shipment_label" name="支付方式">支付方式：</div>
            </el-col>
            <el-col :span="15">
              <el-select v-model="form.payModeItem" value-key="label" placeholder class="full-width-i">
                <el-option
                  v-for="item in payModes"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                />
              </el-select>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-row :gutter="1">
            <el-col :span="5">
              <div class="shipment_label" name="多次收款">多次收款：</div>
            </el-col>
            <el-col :span="15" class="ml-10">
              <el-radio v-model="form.multipleSale" :label="true">是</el-radio>
              <el-radio v-model="form.multipleSale" :label="false">否</el-radio>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="8">
          <el-row :gutter="1">
            <el-col :span="5">
              <div class="shipment_label" name="收款金额">收款金额：</div>
            </el-col>
            <el-col :span="15">
              <el-input v-model="form.orderReceipts" placeholder/>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="8">
          <el-row :gutter="1">
            <el-col :span="5">
              <div class="shipment_label" name="收款日期">收款日期：</div>
            </el-col>
            <el-col :span="15">
              <!-- <el-input v-model="form.createTime" placeholder=""/> -->
              <el-date-picker v-model="form.receivablesTime" class="full-width-i" type="datetime" placeholder="选择日期时间"/>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-row :gutter="1">
            <el-col :span="5">
              <div class="shipment_label" name="用户名称">用户名称：</div>
            </el-col>
            <el-col :span="15">
              <el-input v-model="form.userName" placeholder/>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="8">
          <el-row :gutter="1">
            <el-col :span="5">
              <div class="shipment_label" name="用户电话">用户电话：</div>
            </el-col>
            <el-col :span="15">
              <el-input v-model="form.phone" placeholder/>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="8">
          <el-row :gutter="1">
            <el-col :span="5">
              <div class="shipment_label" name="用户地址">用户地址：</div>
            </el-col>
            <el-col :span="15">
              <el-input v-model="form.address" placeholder/>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row :gutter="20" class="pt-10 pb-20">

        <el-col :span="8">
          <el-row :gutter="1">
            <el-col :span="5">
              <div class="shipment_label" name="收款备注">收款备注：</div>
            </el-col>
            <el-col :span="15">
              <el-input :rows="3" v-model="form.receiptRemark" type="textarea" placeholder/>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="8">
          <el-row :gutter="1">
            <el-col :span="5">
              <div class="shipment_label" name="备注">备注：</div>
            </el-col>
            <el-col :span="15">
              <el-input :rows="3" v-model="form.orderRemark" type="textarea" placeholder/>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>

    <div class="table-ymm">
      <el-table :data="mallOrderItemList" style="width: 100%" border>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-plus"
              type="text"
              size="small"
              @click.native.prevent="addRow(scope.$index+1)"
            />
            <el-button
              icon="el-icon-delete"
              type="text"
              size="small"
              @click.native.prevent="deleteRow(scope.$index)"
            />
            <!-- <el-button type="text" size="small" @click.native.prevent="addRow(tableData)">添加</el-button> -->
            <!-- <el-button type="text" size="small" @click.native.prevent="deleteRow(scope.$index, tableData)">删除</el-button> -->
          </template>
        </el-table-column>
        <el-table-column label="SKU编码">
          <template slot-scope="scope">
            <span>{{ scope.row.skuCode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="条码">
          <template slot-scope="scope">
            <span>{{ scope.row.internationalBarcode }}</span>
          </template>
        </el-table-column>
        <el-table-column label="SKU名称">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.sku"
              :remote-method="getSkuList.bind(null,scope.$index)"
              :loading="loading"
              value-key="skuName"
              filterable
              remote
              reserve-keyword
              placeholder="输入sku名称/编号"
              @change="changeSku(scope.row,scope.$index)"
            >
              <!--  -->
              <el-option
                v-for="item in scope.row.skuList"
                :key="item.skuId"
                :label="item.skuName"
                :value="item"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="数量">
          <template slot-scope="scope">
            <el-input v-model="scope.row.amount" placeholder/>
          </template>
        </el-table-column>
        <el-table-column label="销售单价">
          <template slot-scope="scope">
            <el-input v-model="scope.row.price" placeholder/>
          </template>
        </el-table-column>
        <el-table-column label="实销单价">
          <template slot-scope="scope">
            <el-input v-model="scope.row.sellingPrice" placeholder/>
          </template>
        </el-table-column>
        <el-table-column label="实销小计">
          <template slot-scope="scope">
            <span>{{ (parseFloat(scope.row.sellingPrice?scope.row.sellingPrice:0)*parseFloat(scope.row.amount?scope.row.amount:0)).toFixed(2) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- <div class="table-ymm-bt">
      <el-pagination :current-page="table.current_page" :page-sizes="[10, 20, 30, 40]" :page-size="10" :pager-count="table.page_count" :total="table.total" background layout="sizes, prev, pager, next,total" @current-change="handleCurrentChange"/>
    </div>-->
  </div>
</template>

<script>
import { get, post } from '@/api/utils'
import { message, validatePrice, checkPhone } from '@/utils/utils'

export default {
  data() {
    return {
      modal: null,
      value: '',
      skuList: [],
      loading: false,
      mallOrderItemInit: {},
      deliveryModes: [
        { label: '门店提货', value: '1' },
        { label: '快递', value: '2' }
      ],
      payModes: [
        { label: '支付宝', value: '1' },
        { label: '微信', value: '2' },
        { label: '公司账号', value: '3' }
      ],
      storeList: [],
      mallOrderItemList: [
        {
          mallOrderItemId: null,
          mallOrderId: null,
          mallOrderNumber: null,
          skuId: null,
          skuName: null,
          skuCode: null,
          classification: null,
          commodityState: null,
          sourceDepot: null,
          serialNumber: null,
          amount: null,
          price: null,
          distributableProfit: null,
          shippedAmount: null,
          isBranch: null,
          payPrice: null,
          mallOrderItemIds: null,
          warehouseId: null,
          sku: null,
          address: null,
          orderSource: null,
          deliveryMode: null,
          orderRemark: null,
          shipmentPipelineNumber: null,
          createby: null,
          createTime: null,
          updateby: null,
          updateTime: null,
          deleteFlag: 'N',
          deleteby: null,
          deleteTime: null
        }
      ],
      form: {
        mallOrderId: null,
        deliveryMode: 1,
        payMode: null,
        userName: null,
        phone: null,
        address: null,
        receiptRemark: null,
        orderRemark: null,
        orderReceipts: null,
        multipleSale: false,
        store: null,
        deliveryModeItem: null,
        payModeItem: null
      }
    }
  },
  created() {
    this.getStoreList()
    // var mallOrder = this.$route.params.mallOrder
    var mallOrder = this.$route.query.mallOrder
    if (mallOrder) {
      mallOrder.payModeItem = {
        label: this.payModes
          .map(payModeItem => {
            if (payModeItem.value === mallOrder.payModeItem.value) {
              return payModeItem.label
            }
          })
          .join(''),
        ...mallOrder.payModeItem
      }
      mallOrder.deliveryModeItem = {
        label: this.deliveryModes
          .map(deliveryMode => {
            if (deliveryMode.value && deliveryMode.value === mallOrder.deliveryModeItem.value) {
              return deliveryMode.label
            }
          })
          .join(''),
        ...mallOrder.deliveryModeItem
      }
      if (mallOrder.createTime) {
        mallOrder.createTimeDate = new Date(mallOrder.createTime)
      }
      var mallOrderItemList = this.$route.query.mallOrderItemList
      console.log(mallOrder)
      this.form = { ...this.form, ...mallOrder }

      // Object.assign({} ,this.form, mallOrder)

      // {...mallOrder,...this.form}

      if (mallOrderItemList && mallOrderItemList.length > 0) {
        this.mallOrderItemList = mallOrderItemList.map(mallOrderItem => {
          mallOrderItem.sku = {
            skuName: mallOrderItem.skuName,
            skuId: mallOrderItem.skuId
          }
          mallOrderItem.skuList = [mallOrderItem.sku]
          mallOrderItem.sellingPrice =
            mallOrderItem.payPrice / mallOrderItem.amount
          return mallOrderItem
        })
      }
    }
  },
  methods: {
    goBack() {
      this.$router.back(-1)
    },
    deleteRow(index, rows) {
      this.mallOrderItemList.splice(index, 1)
      // rows.splice(index, 1)
    },
    addRow(index, rows) {
      this.mallOrderItemList.push(this.mallOrderItemInit)
    },
    getSkuList(index, search) {
      this.loading = true
      console.log('---------------' + arguments)
      var data = {}

      if (search !== null) {
        data.search = search
        data.status = 1
      }

      get('/wxh-cloud-rest/rest/', '/pas/sku/list', data)
        .then(response => {
          if (response.data.status === 'success') {
            this.$set(this.mallOrderItemList, index, { ...this.mallOrderItemList[index], 'skuList': response.data.data.skuList })
            this.loading = false
          } else if (response.data.status === 'token_check_faild') {
            this.$message({
              message: response.data.messge,
              type: 'warning'
            })
            this.loading = false
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '数据加载失败',
            type: 'warning'
          })
          this.loading = false
        })
    },

    getStoreList() {
      var data = { deteleFlag: 'N', offset: '0' }

      get('/wxh-cloud-rest/rest/', '/pas/store/queryAllStore', data)
        .then(response => {
          if (response.data.status === 'success') {
            this.storeList = [...response.data.data.list, ...this.storeList]
            var form = this.form
            if (form) {
              if (form.store && form.store.storeId && !form.store.storeName) {
                form.store = {
                  storeName: this.storeList
                    .map(store => {
                      if (store.storeId === form.store.storeId) {
                        return store.storeName
                      }
                    })
                    .join(''),
                  ...form.store
                }
              }
            }
          } else if (response.data.status === 'token_check_faild') {
            message(this, response.data.messge)
          }
        })
        .catch(error => {
          console.log(error)
          message(this, '数据加载失败')
        })
    },

    changeSku(row, index) {
      this.mallOrderItemList.splice(index, 1, { ...row, ...row.sku })
    },

    save(formName) {
      var self = this

      try {
        var form = this.form
        var mallOrder = { 'mallOrderId': form.mallOrderId }

        if (form) {
          if (form.store && form.store.storeId) {
            mallOrder.storeId = form.store.storeId
          } else {
            throw new Error('请选择门店')
          }

          if (form.deliveryModeItem && form.deliveryModeItem.value) {
            mallOrder.deliveryMode = form.deliveryModeItem.value
          } else {
            throw new Error('请选择提货方式')
          }

          if (form.payModeItem && form.payModeItem.value) {
            mallOrder.payMode = form.payModeItem.value
          } else {
            throw new Error('请选择支付方式')
          }

          if (form.orderReceipts !== null) {
            if (validatePrice(form.orderReceipts)) {
              mallOrder.orderReceipts = form.orderReceipts
            } else {
              throw new Error('请输入正确的价格')
            }
          } else {
            throw new Error('请输入收款金额')
          }

          if (form.receivablesTime) {
            // mallOrder.createTime = mallOrder.createTimeDate.getTime()
            mallOrder.receivablesTime = form.receivablesTime
          } else {
            throw new Error('请选择收款时间')
          }

          if (form.userName && form.userName.length > 0) {
            if (form.userName.length <= 50) {
              mallOrder.userName = form.userName
            } else {
              throw new Error('用户名最长50个汉字')
            }
          } else {
            throw new Error('请输入用户名')
          }

          if (form.phone && form.phone.length > 0) {
            if (form.phone.length <= 50) {
              if (checkPhone(form.phone)) {
                mallOrder.phone = form.phone
              } else {
                throw new Error('请输入正确的手机号')
              }
            } else {
              throw new Error('手机号最长50个汉字')
            }
          } else {
            throw new Error('请输入用户电话')
          }

          if (form.address && form.address.length > 0) {
            if (form.address.length < 100) {
              mallOrder.address = form.address
            } else {
              throw new Error('用户地址最长100个汉字')
            }
          } else {
            throw new Error('请输入用户地址')
          }
          if (form.multipleSale && form.multipleSale === true) {
            if (form.receiptRemark === null) {
              throw new Error('多次收款，请输入收款备注')
            }
          }
          mallOrder.multipleSale = form.multipleSale
          mallOrder.receiptRemark = form.receiptRemark

          mallOrder.orderRemark = form.orderRemark

          // delete mallOrder.store
          // delete mallOrder.deliveryModeItem
          // delete mallOrder.sku
          // delete mallOrder.payModeItem
        } else {
          throw new Error('请输入订单相关信息')
        }

        var formData = new FormData()
        var mallOrderItemList = this.mallOrderItemList
        let saleAmount = 0
        if (mallOrderItemList && mallOrderItemList.length > 0) {
          mallOrderItemList = mallOrderItemList.map((mallOrderItem, index) => {
            var mallOrderItem_u = {}
            if (mallOrderItem) {
              var errorMessage = '订单明细第' + (index + 1) + '项,'
              if (!mallOrderItem.skuId) {
                throw new Error(errorMessage + '请输入选择sku')
              }
              if (!mallOrderItem.amount) {
                throw new Error(errorMessage + '请输入数量')
              }
              if (!mallOrderItem.sellingPrice) {
                throw new Error(errorMessage + '请输入实销价格')
              }

              if (!mallOrderItem.price) mallOrderItem.price = 0
              delete mallOrderItem.sku
              mallOrderItem.createTime = null
              mallOrderItem_u.mallOrderId = mallOrderItem.mallOrderId
              mallOrderItem_u.mallOrderItemId = mallOrderItem.mallOrderItemId
              mallOrderItem_u.skuId = mallOrderItem.skuId
              mallOrderItem_u.amount = mallOrderItem.amount
              mallOrderItem_u.price = mallOrderItem.price
              mallOrderItem_u.sellingPrice = mallOrderItem.sellingPrice

              saleAmount += (mallOrderItem.sellingPrice * mallOrderItem.amount)
            } else {
              throw new Error('请输入订单明细项信息')
            }

            // formData.append("orderItemDtos["+index+"]",{"mallOrderItemId":index})
            return mallOrderItem_u
          })
        } else {
          throw new Error('请添加订单明细项')
        }
        if (form.multipleSale === false) {
          var receiptAmount = Number(form.orderReceipts)
          if (isNaN(receiptAmount)) {
            throw new Error('收款金额格式错误')
          }
          if (saleAmount !== receiptAmount) {
            throw new Error('不是多次收款，收款金额必需等于实销总额')
          }
        }
        mallOrder.orderItemDtos = mallOrderItemList

        formData.append('orderItemDtos', mallOrderItemList)
        formData.append('deliveryMode', '1')

        // mallOrder = {'storeId':1}

        // { 'Content-Type': 'multipart/form-data; charset=UTF-8', 'Accept': 'application/json' } 'Content-Type': 'multipart/form-data; charset=UTF-8',     application/x-www-form-urlencoded; charset=UTF-8
        post('/wxh-cloud-rest/rest/', '/pas/mallOrder/editMallOrder', mallOrder)
          .then(response => {
            if (response.data.status === 'success') {
              console.log(response)
              this.$message({
                message: '编辑成功'
              })
              this.$router.push('/pas_order/query')
            } else if (response.data.status === 'token_check_faild') {
              this.$message({
                message: response.data.messge,
                type: 'warning'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.$message({
              message: '数据加载失败',
              type: 'warning'
            })
          })
      } catch (error) {
        // console.log(error.name + ": " + error.message)
        message(self, error.message)
      }
    }
  }
}
</script>

<style >
.el-tabs__content .list > .item {
  margin: 10px 0 0;
  border: 1px solid #e9edf0;
  border-radius: 4px;
  padding: 10px;
  color: #8f97a4;
  font-size: 12px;
}
.el-tabs__content .list > .item > .name {
  color: #1b263a;
  margin-bottom: 10px;
}
.el-tabs__content .list > .item .price {
  font-size: 14px;
}
.el-select--medium {
  width: 100% !important;
}
</style>
